package gateway.route;
import okhttp3.*;

import java.io.IOException;

public class PrometheusPushgatewayDemo {

    private static final MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain; charset=utf-8");
    private static final String PUSHGATEWAY_URL = "http://10.211.55.20:9091/metrics/job/batchjob1_user_counter";

    public static void main(String[] args) {
           String metrics = "batchjob1_user_counter{instance=\"192.168.8.34\",server=\"192.168.8.34\"} 297666\n" +
                "another_metric 54321\n";
           // 写入 prometheus 格式 labels 不能出现  __name__="batchjob1_user_counter"
           // 结尾必须是换行符 \n
        metrics = "batchjob1_user_counter{Manufacturer=\"pushgateway\", exported_instance=\"192.168.8.34\", exported_job=\"batchjob1_user_counter\", idc=\"fj\", instance=\"10.211.55.20:9091\", job=\"pushgateway\", test=\"test\"} 197666";
        pushData(metrics);
    }
    public static void pushData(String metrics){
        OkHttpClient client = new OkHttpClient();

        // 创建一个包含 Prometheus 指标的字符串
//        String metrics = "batchjob1_user_counter{instance=\"192.168.8.34\"} 297666\n" +
//                "another_metric 54321\n";
        // batchjob1_user_counter{Manufacturer="pushgateway", __name__="batchjob1_user_counter", exported_instance="192.168.8.34", exported_job="batchjob1_user_counter", idc="fj", instance="10.211.55.20:9091", job="pushgateway", test="test"} 197666

        RequestBody body = RequestBody.create(MEDIA_TYPE_TEXT, metrics);
        Request request = new Request.Builder()
                .url(PUSHGATEWAY_URL)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            // 打印响应内容，通常 Pushgateway 会返回一个空响应体或简单的确认消息
            String s = response.body().string();
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}